package com.ants.boot.utils;

import java.util.concurrent.*;

/**
 * @author 蚂蚁会花呗
 * @date 2022/1/11 18:03
 */
public class ThreadPoolUtils {

    /**
     * 线程缓冲队列
     */
    private static BlockingQueue<Runnable> blockQueue = new ArrayBlockingQueue<Runnable>(100);

    /**
     * 核心线程数，会一直存活，即使没有任务，线程池也会维护线程的最少数量
     */
    private static final int SIZE_CORE_POOL = 5;
    /**
     * 线程池维护线程的最大数量
     */
    private static final int SIZE_MAX_POOL = 10;
    /**
     * 线程池维护线程所允许的空闲时间
     */
    private static final long ALIVE_TIME = 60;

    private static ThreadPoolExecutor pool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME, TimeUnit.SECONDS, blockQueue, new ThreadPoolExecutor.CallerRunsPolicy());

    static {
        //启动所有核心线程，使它们空闲等待工作
        pool.prestartAllCoreThreads();
    }
    public static ThreadPoolExecutor getPool() {
        return pool;
    }

    /**
     * 无返回值执行
     * @param runnable
     */
    public static void execute(Runnable runnable){
        pool.execute(runnable);
    }

    /**
     * 需要有返回值执行
     * @param callable
     * @param <T>
     * @return
     */
    public static<T> Future<T> submit(Callable<T> callable){
        return pool.submit(callable);
    }



}
